﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Module.Common.Models;
using Module.Core.BusinessLogic.CmsContents;
using Module.Core.BusinessLogic.Products;
using Module.Core.Common;
using Module.Core.EntitiesInfo.TablesInfo;
using Module.Core.LoginSystem.Commons.Framwork;



namespace Web.Cms.Products
{
    public partial class LstProducts : AdminUserControl
    {


        #region Khai báo biến
        private int totalRecords;
        private int cPage = 1;
        private int page;
         private  string keyword;
        private int checkType;
        private int ZoneId;
        private DateTime dateTo ;
        private DateTime dateFrom;
       #endregion

        #region OnInit
        protected override void OnInit(EventArgs e)
        {
            try
            {
                base.OnInit(e);
                CMSZonesBL.GetDataComboType(dropZoneId, "0", "(" + ModulType.SanPham.Type.ToString() + ")");//BinCombo Cateid                       
                if (Request.QueryString["zoneId"] != null || Request.QueryString["zoneId"] != "")
                {
                    dropZoneId.SelectedValue = Request.QueryString["zoneId"];
                }

                //if (Request.QueryString["checkType"] != null || Request.QueryString["checkType"] != "")
                //{
                //    dropCheckType.SelectedValue = Request.QueryString["checkType"];
                //}
                if (Request.QueryString["keyword"] != null || Request.QueryString["keyword"] != "")
                    txtKeysearch.Text = Request.QueryString["keyword"];

                if (Request.QueryString["dateFrom"] != null && Request.QueryString["dateFrom"] != "")
                {
                    dateFrom = Convert.ToDateTime(Request.QueryString["dateFrom"].Trim());
                    txtDatefrom.Text = dateFrom.ToString("MM/dd/yyyy");
                }
                else
                {
                    dateFrom = DateTime.Now.AddMonths(-2);
                    txtDatefrom.Text = dateFrom.ToString("MM/dd/yyyy");
                }

                if (Request.QueryString["dateTo"] != null && Request.QueryString["dateTo"] != "")
                {
                    dateTo = Convert.ToDateTime(Request.QueryString["dateTo"].Trim());
                    txtDateTo.Text = dateTo.ToString("MM/dd/yyyy");
                }
                else
                {
                    dateTo = DateTime.Now.AddMonths(+1);
                    txtDateTo.Text = dateTo.ToString("MM/dd/yyyy");
                }
            }
            catch (Exception ex)
            {
                lblMessage.Text = "Error: " + ex.Message;
            }
        }
        #endregion

        #region OnPreRender
        protected override void OnPreRender(EventArgs e)
        {
            try
            {              
                base.OnPreRender(e);
                LoadData();
            }
            catch (Exception ex)
            {
                lblMessage.Text = ex.Message;
            }

        }
        #endregion

        #region LoadData
        private void LoadData()
        {

            totalRecords = ProductsBL.SelectCount(status, txtKeysearch.Text, int.Parse(dropZoneId.SelectedValue), DateTime.Parse(txtDatefrom.Text), DateTime.Parse(txtDateTo.Text).AddDays(+1));
            lbTotal.Text = "Tổng số bản ghi: " + totalRecords;
            DataTable dt;
            if (Request.QueryString.Get("cpage") != null)
                cPage = ObjConvertUtility.ToInt32(Request.QueryString.Get("cPage"));
            if (cPage == 0) cPage = 1;
            int from = (cPage - 1) * Const.pageSize20 + 1;
            if (from == 0) from = 1;
            int to = (cPage) * Const.pageSize20;

            PagingAjax1.totalRecords = totalRecords;
            PagingAjax1.numPerPage = Const.pageSize20;
            PagingAjax1.queryParam = ObjMiscUtility.GetCPPage(CurrentCommand.CtrlKey,
                                    new string[] { "ProductName", "zoneId", "from", "to", "dateFrom", "dateTo", "cPage" },
                                    new string[] { txtKeysearch.Text, dropZoneId.SelectedValue, from.ToString(), to.ToString(), dateFrom.ToString(), dateTo.ToString(), "" });

            PagingAjax1.defaultQueryParam =
                ObjMiscUtility.GetCPPage(CurrentCommand.CtrlKey,
                                    new string[] { "ProductName", "from", "to" },
                                    new string[] { txtKeysearch.Text, from.ToString(), to.ToString() });

            string order = null;
            dt = ProductsBL.Search(status, txtKeysearch.Text, int.Parse(dropZoneId.SelectedValue), DateTime.Parse(txtDatefrom.Text), DateTime.Parse(txtDateTo.Text).AddDays(+1), from, to, order);
            if (dt != null && dt.Rows.Count > 0)
            {

                grdProduct.DataSource = dt;
                grdProduct.RowDataBound += new GridViewRowEventHandler(grdProduct_RowDataBound);
                grdProduct.DataBind();

            }
        }
        #endregion


        #region RowDataBound
        protected void grdProduct_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ImageButton btnStatus = (ImageButton)e.Row.FindControl("btnStatus");
                ImageButton img = (ImageButton)e.Row.FindControl("img");
                DataRowView dr = (DataRowView)e.Row.DataItem;

                e.Row.Cells[0].Text = (Const.pageSize20 * (cPage - 1) + e.Row.DataItemIndex + 1).ToString();
                if (dr["AvatarSmail"].ToString().Length > 0)
                {
                    img.Visible = true;
                    img.ImageUrl = dr["AvatarSmail"].ToString();
                }
               if(dr["AvatarBig"].ToString().Length>0)
               {
                   img.Visible = true;
                   img.ImageUrl = dr["AvatarSmail"].ToString();

               }

               if (status == 1)
               {
                   btnStatus.ImageUrl = "/App_Themes/Default/Images/Buttons/btn_pending.gif";
                   btnStatus.OnClientClick = "return confirm('Bạn có chắc chắn gỡ sản phẩm này xuống không ?')";
               }
               else if (status == 2)
               {
                   btnStatus.ImageUrl = "/App_Themes/Default/Images/Buttons/btn_forward.gif";
                   btnStatus.OnClientClick = "return confirm('Bạn có muốn khôi phục lại sản phẩm này không ?')";
               }
               else if (status == 3)
               {
                   btnStatus.ImageUrl = "/App_Themes/Default/Images/Buttons/btn_forward.gif";
                   btnStatus.OnClientClick = "return confirm('Bạn có muốn đăng sản phẩm này không?')";
               }          
            }
        }

        #endregion
       
        #region RowCommand

        protected void grdProduct_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                switch (e.CommandName)
                {
                    case "CommandStatus":
                        try
                        {
                            int productId = Convert.ToInt32(e.CommandArgument);
                           
                            if (status == 3)// Sản phẩm đang chờ duyệt -> khi đưa lên web update status=1
                            {
                                ProductsBL.UpdateAllProducts(productId,1,1);
                            }
                            else if (status == 1)// Sản phẩm hiển thị trên website -> gỡ xuống update status=2
                            {
                                ProductsBL.UpdateAllProducts(productId, 1, 2);
                            }
                            else if (status == 2)//sản phẩm đang ở trạng thái ngừng hiển thị-> update status=3
                            {
                                ProductsBL.UpdateAllProducts(productId,1,3);
                            }
                        }
                        catch (Exception ex)
                        {
                            lblMessage.Text = ex.Message;
                        }
                        break;

                    case "Commanddelete":
                        try
                        {
                            int productId = Convert.ToInt32(e.CommandArgument);
                            ProductsBL.Delete(productId);
                            LoadData();
                        }
                        catch (Exception ex)
                        {
                            lblMessage.Text = ex.Message;
                        }
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                lblMessage.Text = ex.Message;
            }
        }
      
        #endregion

        #region tìm kiếm
        protected void btnTimKiem_Click(object sender, EventArgs e)
        {
            Response.Redirect("Default.aspx?ctrlkey=" + CurrentCommand.CtrlKey + "&keyword=" + txtKeysearch.Text.Trim() + "&ZoneId=" + dropZoneId.SelectedValue + "&dateFrom=" + txtDatefrom.Text.Trim() + "&dateTo=" + txtDateTo.Text.Trim());
            
        }
        #endregion

        private int status;
        public int Status
        {
            set { status = value; }
            get { return status; }
        }

    }
}